package cn.dengta.webapp.user.service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;

import cn.dengta.common.model.TimeInterval;
import cn.dengta.context.model.UserI18nKey;
import cn.dengta.webapp.base.service.BaseServiceImpl;
import cn.dengta.webapp.user.dao.UserLoginStatisticsDao;
import cn.dengta.webapp.user.entity.User;
import cn.dengta.webapp.user.entity.UserLoginStatistics;
import me.codeplayer.util.EasyDate;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 用户登录统计 服务实现类
 *
 * @author zw
 * @since 2022-10-09
 */
@Service
public class UserLoginStatisticsService extends BaseServiceImpl<UserLoginStatistics, UserLoginStatisticsDao, Long> {

	@Resource
	StringRedisTemplate stringRedisTemplate;

	public boolean statistics(User sessionUser) {
		if (sessionUser.getGender() == null) {
			return false;
		}
		final Long userId = sessionUser.getId();
		final EasyDate d = new EasyDate();
		final HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
		final String key = UserI18nKey.DAY_LOGIN_INFO + d.getDay();
		final Date now = d.toDate();
		boolean flag = Boolean.FALSE.equals(opsForHash.hasKey(key, sessionUser.idStr()));
		if (flag) {
			opsForHash.put(key, sessionUser.idStr(), "1");
			stringRedisTemplate.expire(key, d.setDate(now).endOf(Calendar.DAY_OF_MONTH).addMinute(5).getTime() - now.getTime(), TimeUnit.MILLISECONDS);

			UserLoginStatistics userLoginStatistics = baseDao.selectById(sessionUser.getId());
			if (userLoginStatistics == null) {
				userLoginStatistics = UserLoginStatistics.of(sessionUser, now);
				baseDao.insert(userLoginStatistics);
			} else {
				final int continuous = isContinuousLogin(userLoginStatistics.getLastLoginTime(), now);
				if (continuous > 0) {
					baseDao.updateLoginCount(userId, now, continuous == 1 ? 1 : 0);
				} else {
					baseDao.updateLoginTimes(userId, now);
				}
			}
		} else {
			baseDao.updateLoginTimes(userId, now);
		}
		return flag;
	}

	private int isContinuousLogin(Date lastLoginTime, Date now) {
		return new EasyDate(now).calcDifference(lastLoginTime);
	}

	/**
	 * 获取连续登录用户
	 */
	public List<UserLoginStatistics> findContinuousLogin(TimeInterval lastLoginTime) {
		return this.getBaseDao().findContinuousLogin(lastLoginTime);
	}

}
